<!DOCTYPE html>
<html lang="zh">

<head>
  <th:block th:include="include :: header('场景类型监测')" />
  <th:block th:include="include :: layout-latest-css" />
  <th:block th:include="include :: ztree-css" />
  <link rel="stylesheet" th:href="@{/css/scenarioCate.css}" href="/css/scenarioCate.css" />
</head>
<style>
  .bootstrap-table .fixed-table-container .fixed-table-body {
    height: 492px;
  }

  .fixed-table-body {
    border: 1px solid #ccc;
  }

  .table-striped table>thead>tr>th,
  .table-striped table>tbody>tr>th,
  .table-striped table>tfoot>tr>th,
  .table-striped table>thead>tr>td,
  .table-striped table>tbody>tr>td,
  .table-striped table>tfoot>tr>td {
    border: 1px solid #e7eaec;
  }
</style>

<body class="gray-bg">
  <div class="ui-layout-west">
    <div class="box box-main">
      <div class="box-header">
        <div class="box-title"><i class="fa icon-grid"></i>场景监测</div>
        <div class="box-tools pull-right">
          <a type="button" class="btn btn-box-tool" href="#" onclick="dept()" title="管理部门"><i
              class="fa fa-edit"></i></a>
          <button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display: none">
            <i class="fa fa-chevron-up"></i>
          </button>
          <button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠">
            <i class="fa fa-chevron-down"></i>
          </button>
          <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新部门">
            <i class="fa fa-refresh"></i>
          </button>
        </div>
      </div>
      <div class="ui-layout-content">
        <div id="tree" class="ztree"></div>
      </div>
    </div>
  </div>

  <div class="ui-layout-center">
    <div class="container-div">
      <div class="row">
        <div class="col-sm-12 select-table table-striped">
          <div class="bottom">
            <div class="buttonCard">
              <div class="leftChart search-collapse">
                <div class="title">
                  <p>数据统计饼状图</p>
                </div>
                <h3 class="titleErr" style="text-align: center; line-height: 220px; display: none">
                  暂无数据
                </h3>
                <div class="echarsbox">
                  <div id="cake" style="width: 100%; height: 240px"></div>
                </div>
              </div>
              <div class="rightChart search-collapse">
                <div class="title">
                  <p>数据异常柱状图</p>
                </div>
                <h3 class="titleErr" style="text-align: center; line-height: 220px; display: none">
                  暂无数据
                </h3>
                <div class="echarsbox">
                  <div id="main" style="width: 95%; height: 240px"></div>
                </div>
              </div>
            </div>
            <div class="rightCard search-collapse table-striped" style="display: flex; flex-direction: column">
              <form id="user-form">
                <input type="hidden" id="workspaceCategoryId" name="sceneId" />
              </form>
              <div>
                <div class="title">
                  <p>场景实时监测</p>
                </div>
                <table id="bootstrap-table1"></table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 图表 -->
  </div>

  <th:block th:include="include :: footer" />
  <th:block th:include="include :: layout-latest-js" />
  <th:block th:include="include :: ztree-js" />
  <script src="/js/layui.js" th:src="@{/js/layui.js}"></script>
  <script src="/js/echarts.min.js" th:href="@{/js/echart.min.js}"></script>
  <script src="/js/echarts.js" th:src="@{/js/echarts.js}"></script>
  <script th:inline="javascript">
    // var editFlag = [[${@permission.hasPermi('youtianNew:basicsMangement:edit')}]];
    // var removeFlag = [[${@permission.hasPermi('system:user:remove')}]];
    // var resetPwdFlag = [[${@permission.hasPermi('system:user:resetPwd')}]];
    var treeClick = null;
    var ejdw_id = null;//组织机构一级id
    var zyq_id = null;//组织机构二级id
    var dw_3_id = null;//组织机构三级id
    var scene_id = null;//场景id
    var sceneName = null;
    $(function () {
      var panehHidden = false;
      if ($(this).width() < 769) {
        panehHidden = true;
      }
      $("body").layout({ initClosed: panehHidden, west__size: 185 });
      // 回到顶部绑定
      if ($.fn.toTop !== undefined) {
        var opt = {
          win: $(".ui-layout-center"),
          doc: $(".ui-layout-center"),
        };
        $("#scroll-up").toTop(opt);
      }
      renderChart();
      queryDeptTree();
      queryUserList();
      cake()
      load()
    });
    // 渲染左侧树
    function queryDeptTree() {
      var options = {
        // url: "/youtian/scene-category/ztree",
        url: '/gzmx_scdw/gzmx_scdw/temlateTreeDataNew',
        // method:'get',
        expandLevel: 2,
        onClick: zOnClick,
      };
      let ab = $.tree.init(options);

      function zOnClick(event, treeId, treeNode) {
        treeClick = treeNode;
        var getId = treeNode.id
        var getLevel = treeNode.level;
        var initKey = {
          "0": "ejdw_id",
          "1": "zyq_id",
          "2": "dw_3_id",
          "3": "scene_id"
        }
        // 重新设置隐藏from 表单隐藏域的值
        for (const idKey in initKey) {
          console.log(initKey[idKey], '=======');
          // var idName = initKey[idKey];
          // $(`#${idName}`).val('');
          if (idKey == getLevel) {

            var getId = treeNode.id
            var ID = getId.toString().split('3832000000');
            var SceID;
            SceID = ID[ID.length - 1];
            // initKey[idKey] = SceID;
            let obj = {}
            obj[initKey[idKey]] = SceID
            if (idKey == '3') {
              sceneName = treeNode.name
              obj.sceneName = sceneName
            }
            $("#workspaceCategoryId").val(SceID);
            renderChart(obj);
            cake(obj)
          }
        }
        // var getId = treeNode.id
        // var ID = getId.toString().split('3832000000');
        // var SceID;
        // SceID = ID[ID.length - 1];

        $.table.search();

      }
    }

    $("#btnExpand").click(function () {
      $._tree.expandAll(true);
      $(this).hide();
      $("#btnCollapse").show();
    });

    $("#btnCollapse").click(function () {
      $._tree.expandAll(false);
      $(this).hide();
      $("#btnExpand").show();
    });

    $("#btnRefresh").click(function () {
      queryDeptTree();
    });
    // 场景右侧检测图表

    function renderChart(obj) {
      console.log(obj);
      $.ajax({
        // url: `/youtian/scene-category/getSceneCategory?categoryId=${id ? id : "1"}`,
        url: `/youtian/workspace-category/getColumndiagram`,
        // method: 'post',
        // dataType:'json',
        data: obj,
        type: "get",
        success: function (res) {
          console.log(res, '柱图');
          if (res.data.length <= 0) {
            $(".titleErr").css("display", "block");
            $(".echarsbox").css("display", "none");
            return;
          } else {
            $(".titleErr").css("display", "none");
            $(".echarsbox").css("display", "block");
          }
          let echartData = res.data;
          // 柱状图
          var chartDom = document.getElementById("main");
          var myChart = echarts.init(chartDom);
          var option;
          let echartY = [];
          let errorTagCount = [];
          let tagCount = [];
          echartData.forEach((item) => {
            echartY.push(item.name);
            errorTagCount.push(item.pointsum);
            tagCount.push(item.police);
          });
          option = {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
              },
            },
            legend: {},
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            xAxis: {
              type: "value",
              name: "数量",
            },
            yAxis: {
              type: "category",
              name: "场景名称",
              data: echartY,
            },
            series: [
              {
                name: "异常数量",
                type: "bar",
                stack: "total",
                label: {
                  show: true,
                },
                emphasis: {
                  focus: "series",
                },
                data: errorTagCount,
              },

              {
                name: "监测点数量",
                type: "bar",
                stack: "total",
                label: {
                  show: true,
                },
                emphasis: {
                  focus: "series",
                },
                data: tagCount,
              },
            ],
          };

          option && myChart.setOption(option);

          // 饼状图

        },
      });
    }

    // 饼状图表格
    function cake(obj) {
      console.log(obj);
      $.ajax({
        url: '/youtian/workspace-category/getPieChart',
        data: obj,
        success: function (res) {
          let cakeArray = []
          res.data.forEach(item => {
            console.log(item);
            cakeArray.push(item.pointsum)
          })
          var chartDom = document.getElementById("cake");
          var myChart = echarts.init(chartDom);
          var option;
          option = {
            title: {
              text: "数据统计饼状图",
              left: "center",
            },
            tooltip: {
              trigger: "item",
            },
            legend: {
              orient: "vertical",
              left: "left",
            },
            series: [
              {
                name: "场景名称",
                type: "pie",
                radius: "50%",
                data: pieChartData(res.data),
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                  },
                },
              },
            ],
          };
          $(".isShow").css({
            display: "none",
          });
          option && myChart.setOption(option);
        }
      })
    }




    function queryUserList(id) {
      console.log(id, "id");
      var options = {
        id: "bootstrap-table1",
        url: `/youtian/scene-category/scencePointlistNoPage`,
        method: "get",
        bordered: true,
        showSearch: false,
        modalName: "用户",
        onClickRow: onClickRow,
        onLoadSuccess: function (data) {
          mergeCells(data, "sceneName", 1, $("#bootstrap-table1")); //行合并
        },
        rowStyle: function (row, index) {
          var classes = ["bg-blue", "bg-green", "bg-red"];
          if (row.dataState != "异常") {
            return {
              classes: classes[index / 2],
            };
          }
          return {
            css: {
              color: "red",
            },
          };
        },
        columns: [
          {
            field: "sceneName",
            title: "场景名称",
            align: "center",
          },
          {
            field: "pointName",
            title: "采集数据点位",
            align: "center",
          },
          {
            field: "upperLimit",
            title: "上限值",
            align: "center",
          },
          {
            field: "lowerLimit",
            title: "下限值",
            align: "center",
          },
          {
            field: "dataState",
            title: "数据状态",
            align: "center",
          },
          {
            field: "value",
            title: "采集值",
            align: "center",
          },
        ],
      };
      $.table.init(options);
    }

    // 点击表格显示图表
    // 定时器
    var setTimeData = "";
    let list = {};
    $('#bootstrap-table1').mouseleave(function () {
      clearInterval(setTimeData)
      $("#noneBox").remove()
    })
    function onClickRow(row, el) {
      clearInterval(setTimeData);
      let echartDom = el.children("#noneBox");
      console.log(echartDom[0], "echartDom");
      if (echartDom[0]) {
        return echartDom.remove();
      }
      console.log(row, "row");
      let sourceTag = row.pointId;
      list = {
        sourceTag: sourceTag,
        params: {
          beginTime: "",
          endTime: "",
        },
      };
      console.log(list, "list");
      // $.ajax({
      //   url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
      //   type: "post",
      //   dataType: "json",
      //   data: JSON.stringify(list),
      //   headers: { "Content-Type": "application/json" },
      //   success: function (res) {
      //     console.log(res, "res");
      //     el.mouseleave(function () {
      //       console.log(el.children("td"), el.children("td").eq(3), '123');
      //       $(".tip_text").remove();
      //     });
      //     if (res.data.length <= 0) {
      //       $(".tip_text").remove();
      //       return el.append(`<div class="tip_text">暂无数据</div>`);
      //     }
      //     $("#noneBox").remove();
      //     el.append(`<div id="noneBox"></div>`);
      //     let upLimit = el.children("td").eq(2).text();
      //     let lowLimit = el.children("td").eq(3).text();
      //     echart(parseInt(upLimit), parseInt(lowLimit), res.data);
      //   },
      // });
    }

    // 封装图表方法
    // function echart(upLimit, lowlimit, options) {
    //   // let optionsSlice = options.slice(10, 20)
    //   // console.log(optionsSlice, 'optionsSlice');
    //   // // 图表数据
    //   // let dataLists = {
    //   //   data: [],
    //   //   cjTime: []
    //   // }
    //   // optionsSlice.forEach(item => {
    //   //   dataLists.data.push(item.value)
    //   //   dataLists.cjTime.push(item.cjTime)
    //   // })

    //   // // 页面最大值
    //   // let dataList = []
    //   // optionsSlice.forEach(item => {
    //   //   dataList.push(item.value)
    //   // });
    //   // dataList.sort((a, b) => {
    //   //   return b -a
    //   // })
    //   // console.log(dataList, 'dataList');
    //   var chartDom = document.getElementById("noneBox");
    //   var myChart = echarts.init(chartDom);
    //   var option;
    //   option = {
    //     tooltip: {
    //       trigger: "axis",
    //       boundaryGap: false,
    //     },
    //     xAxis: {
    //       name: "时间",
    //       type: "category",
    //       boundaryGap: false,
    //       data: ["1-1", "1-2", "1-3", "1-4", "1-5"],
    //     },
    //     yAxis: {
    //       name: "数量",
    //       type: "value",
    //       min: 0,
    //       max: 200,
    //       splitLine: {
    //         show: false,
    //       },
    //     },
    //     grid: {
    //       left: "15%",
    //       right: "20%",
    //       bottom: "10%",
    //       top: "20%",
    //     },
    //     visualMap: [
    //       {
    //         type: "piecewise",
    //         show: false,
    //         dimension: 1,
    //         seriesIndex: 0,
    //         hoverLink: true,
    //         pieces: [
    //           {
    //             // 不指定 min，表示 min 为无限大（-Infinity）。
    //             max: lowlimit, // 没有设置最小值，表明当前范围 [-Infinity, max] 变色
    //             color: "red",
    //           },
    //           {
    //             // 不指定 max，表示 max 为无限大（Infinity）。
    //             min: upLimit, // 没有设置最大值，表明当前范围 [min, Infinity] 变色
    //             color: "red",
    //           },
    //         ],
    //         outOfRange: {
    //           // 在选中范围外 的视觉元素，这里设置在正常范围内的图形颜色
    //           color: "blue",
    //         },
    //       },
    //     ],
    //     series: [
    //       {
    //         type: "line",
    //         smooth: true,
    //         symbol: "none",
    //         markLine: {
    //           symbol: "none",
    //           label: {
    //             show: true,
    //           },
    //           data: [
    //             {
    //               yAxis: lowlimit,
    //             },
    //             {
    //               yAxis: upLimit,
    //             },
    //           ],
    //         },
    //         // areaStyle: {},
    //         data: [10, 15, 140, 40, 150],
    //       },
    //     ],
    //   };
    //   option && myChart.setOption(option);
    //   setTimeData = setInterval(() => {
    //     $.ajax({
    //       url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
    //       type: "post",
    //       dataType: "json",
    //       data: JSON.stringify(list),
    //       headers: { "Content-Type": "application/json" },
    //       success: function (res) {
    //         console.log(res, "length2");
    //         if (res.data && res.data.length) {
    //           option.series[0].data = [3, 45, 3, 45, 33];
    //           option && myChart.setOption(option);
    //         }
    //       },
    //     });
    //   }, 5000);
    // }

    /**
     * 合并行
     * @param data  原始数据（在服务端完成排序）
     * @param fieldName 合并属性名称
     * @param colspan 列数
     * @param target 目标表格对象
     */
    function mergeCells(data, fieldName, colspan, target) {
      // console.log(data, fieldName, colspan, target, '-------');
      data = data.rows
      // console.log(data[0], 'data');
      if (data.length == 0) {
        return;
      }
      var numArr = [];
      var value = data[0][fieldName];
      console.log(value, 'value');
      var num = 0;
      for (var i = 0; i < data.length; i++) {
        if (value != data[i][fieldName]) {
          numArr.push(num);
          value = data[i][fieldName];
          num = 1;
          continue;
        }
        num++;
      }
      if (typeof value != "undefined" && value != "") {
        numArr.push(num);
      }
      var merIndex = 0;
      for (var i = 0; i < numArr.length; i++) {
        $(target).bootstrapTable("mergeCells", {
          index: merIndex,
          field: fieldName,
          colspan: colspan,
          rowspan: numArr[i],
        });
        merIndex += numArr[i];
      }
    }
    // 计算比例
    function pieChartData(arr) {
      console.log(arr, 'arr');
      let total = arr.reduce((prev, next) => {
        console.log();
        return next.pointsum + prev;
      }, 0);
      console.log(total, '-----');
      var newArr = [];
      arr.forEach((item) => {

        var obj = {};
        obj.value = (item.pointsum / total).toFixed(2) * total;
        console.log(obj.value);
        obj.name = item.name;
        newArr.push(obj);
      });
      return newArr;
      console.log(newArr, "newArr");
    }

    //当进入页面时监听当前页面，开启倒计时
    var countDown;
    $(document).ready(function () {
      // 在这里写你的代码...
      countDown = setInterval(() => {
        renderChart()
        cake()
        console.log('倒计时执行');
      }, 60000)
    })
    //离开页面时关闭倒计时
    function load() {
      // 监听 visibility change 事件 
      document.addEventListener('visibilitychange', function () {
        console.log(document.visibilityState, '----->>>>');
        // 页面变为不可见时触发 
        if (document.visibilityState == 'hidden') {
          clearInterval(countDown)
        }
      })
    }
  </script>
</body>

</html>